import axios from "axios";
import { MessagePlugin, LoadingPlugin } from "tdesign-vue";

let toast = null; //loading
const SingleLoading = {
  load: null,
  count: 0,
  startLoading() {
    if (!this.load) {
      console.log("loading start", this.count);
      this.load = LoadingPlugin(true);
    }
    // eslint-disable-next-line no-plusplus
    this.count++;
  },
  endLoading(stopNow) {
    // eslint-disable-next-line no-plusplus
    this.count--;
    if (this.load && (this.count === 0 || stopNow)) {
      console.log("loading end");
      this.count = 0;
      this.load = LoadingPlugin(false);
      this.load = null;
    }
  },
};

var service = axios.create({
  baseURL: process.env.VUE_APP_API_BASE_URL, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000, // request timeout
  headers: {
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Headers":
      "X-Requested-With, content-type, Authorization",
  },
});
// 请拦截
service.interceptors.request.use(
  (config) => {
    const newConf = config;
    if (newConf.loading) {
      SingleLoading.startLoading();
    }
    const { url } = newConf;
    if (url.indexOf("?") !== -1) {
      newConf.url = `${url}&t=${new Date().getTime()}`; // 请求添加时间戳
    } else {
      newConf.url = `${url}?t=${new Date().getTime()}`;
    }
    // get请求映射params参数
    if (newConf.method === "get" && newConf.params) {
      let url = `${newConf.url}?`;
      for (const propName of Object.keys(newConf.params)) {
        const value = newConf.params[propName];
        const part = `${encodeURIComponent(propName)}=`;
        if (value !== null && typeof value !== "undefined") {
          if (typeof value === "object") {
            for (const key of Object.keys(value)) {
              const params = `${propName}[${key}]`;
              const subPart = `${encodeURIComponent(params)}=`;
              url += `${subPart + encodeURIComponent(value[key])}&`;
            }
          } else {
            url += `${part + encodeURIComponent(value)}&`;
          }
        }
      }
      url = url.slice(0, -1);
      newConf.params = {};
      newConf.url = url;
    }
    return newConf;
  },
  (error) => {
    // do something with request error
    toast.clear(); //清除loading
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// 响应拦截
service.interceptors.response.use(
  (res) => {
    if (res.reqConfig?.loading || res.config?.loading) {
      SingleLoading.endLoading();
    }
    // 未设置状态码则默认成功状态
    const { code } = res.data;
    // 获取错误信息
    const msg = res.data.msg || "系统未知错误，请反馈给管理员";
    if (code === 401) {
      // 未认证
      return Promise.reject("无效的会话，或者会话已过期，请重新登录。");
    }
    if (res.config.url.indexOf("/lqsq/v1/getSqmValidResult") > -1) {
      if (code === null || code === "null") {
        return res.data;
      }
    }
    if (code !== 0) {
      MessagePlugin.error({
        content: msg,
        duration: 2000,
      });
      return Promise.reject("error");
    }
    return res.data;

    // console.log(res)
    // if the custom code is not 20000, it is judged as an error.
  },
  (err) => {
    if (
      err.reqConfig?.loading ||
      err.config?.loading ||
      SingleLoading.load !== null
    ) {
      SingleLoading.endLoading(true);
    }
    let { message } = err;
    if (message === "Network Error") {
      message = "后端接口连接异常";
    } else if (message.includes("timeout")) {
      message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
      message = `系统接口${message.substr(message.length - 3)}异常`;
    }
    MessagePlugin.error({
      content: message,
      duration: 5 * 1000,
    });
    return Promise.reject(err);
  }
);

/**
 * 新版Api统一请求入口
 * @param options
 * @param custom
 */
const fetch = (options, custom) => {
  return service(
    {
      ...options,
    },
    custom
  );
};

export { fetch };
